<template>
  <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
  >
    <el-form-item label="手机号" prop="mobile">
      <el-input v-model="ruleForm.mobile" />
    </el-form-item>
    <el-form-item label="密码" prop="pass">
      <el-input v-model="ruleForm.pass" type="password" autocomplete="off" />
    </el-form-item>
    <el-form-item label="确认密码" prop="checkPass">
      <el-input
          v-model="ruleForm.checkPass"
          type="password"
          autocomplete="off"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)"
      >注册</el-button
      >
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance } from 'element-plus'
import axios from "axios";

const ruleFormRef = ref<FormInstance>()

//校验手机号
const checkMobile = (rule: any, value: any, callback: any) => {
  if (!value) {
    return callback(new Error('请输入手机号！'))
  }
}

//校验密码
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码！'))
  } else {
    if (ruleForm.checkPass !== '') {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField('checkPass', () => null)
    }
    callback()
  }
}

//校验两次密码是否一致
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码！'))
  } else if (value !== ruleForm.pass) {
    callback(new Error("两次密码不一致！"))
  } else {
    callback()
  }
}

//注册需要的参数
const ruleForm = reactive({
  mobile: '',
  pass: '',
  checkPass: '',
})

//校验规则
const rules = reactive({
  mobile: [{ validator: checkMobile, trigger: 'blur' }],
  pass: [{ validator: validatePass, trigger: 'blur' }],
  checkPass: [{ validator: validatePass2, trigger: 'blur' }],
})

//注册
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    console.log("666:"+valid)
    if (valid) {
      console.log('注册成功')
      axios.post("http://localhost:5003/user/register",ruleForm).then((res)=>{
        console.log(res)
      })
    } else {
      console.log('注册失败！')
      return false
    }
  })
}

//重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
